//
//  StudyRecordController.m
//  TrainTree
//
//  Created by wanghui on 2017/9/11.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "StudyRecordController.h"
#import "StudyRecordTypeCell.h"
#import "StudyRecordToolCell.h"
#import "QuickLookFileController.h"
#import "MineRequestManager.h"
#import "CourseDetailController.h"
@interface StudyRecordController ()<UITableViewDelegate, UITableViewDataSource,QuickLookDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(assign,nonatomic)BOOL isShow;
@property(strong,nonatomic)NSArray *mainArray;
@end

@implementation StudyRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    self.navigationView.title = @"学习记录";
    self.navigationView.titleIcon.hidden = YES;

    [self.navigationView.leftBtn setImage:ImageNamed(@"backBlack") forState:UIControlStateNormal];
    [self.navigationView.leftBtn addTarget:self action:@selector(backToLastPage) forControlEvents:UIControlEventTouchUpInside];
    [self.tableView registerNib:[UINib nibWithNibName:@"StudyRecordTypeCell" bundle:nil] forCellReuseIdentifier:@"StudyRecordTypeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"StudyRecordToolCell" bundle:nil] forCellReuseIdentifier:@"StudyRecordToolCell"];
    [self requestStudyRecord];
}
- (void)requestStudyRecord
{   WeakSelf(ws);
    [MineRequestManager requestStudyRecordResponse:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        if ([JSONData[@"c"] intValue] == 0) {
            ws.mainArray = JSONData[@"d"];
            [ws.tableView reloadData];

        }
    }];
}
- (void)backToLastPage
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.mainArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *toolArray = [NSArray arrayWithArray:self.mainArray[section][@"tools"]];
    // 工具条数 + 1(课程)
    return toolArray.count + 1;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) {
        return 100.0f;
    } else {
        return 42.0f;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 8.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    NSArray *toolArray = [NSArray arrayWithArray:self.mainArray[section][@"tools"]];
    if (toolArray.count > 3) {
        return 24.0f;
    } else {
        return 0.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView* castView = [[UITableViewHeaderFooterView alloc]init];
    UIView* content = castView.contentView;
    UIColor* color = rgb(249.0f, 249.0f, 249.0f);
    content.backgroundColor = color;
    return castView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
#warning 根据每组对应的Model，有大于三条就显示更多，否则不显示，给按钮添加点击事件将section传过去，刷新对应的section。
    NSArray *toolArray = [NSArray arrayWithArray:self.mainArray[section][@"tools"]];

    if(toolArray.count > 3) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 24.0f)];
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 24.0f)];
        btn.layer.borderWidth = 1.0f;
        btn.layer.masksToBounds = YES;
        btn.backgroundColor = [UIColor whiteColor];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        if(!self.isShow){
            [btn setTitle:@"展开全部" forState:UIControlStateNormal];
        }else{
            [btn setTitle:@"收起" forState:UIControlStateNormal];
        }

        btn.layer.borderColor = rgb(216.0f, 216.0f, 216.0f).CGColor;
        [btn setTitleColor:rgb(164.0f, 164.0f, 164.0f) forState:UIControlStateNormal];
        // 将section跟随按钮传过去
        objc_setAssociatedObject(btn, "section", [NSString stringWithFormat:@"%ld",section], OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC

        [btn addTarget:self action:@selector(reloadCurrentSection:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn];

        return view;
    } else {
        return nil;
    }
}

#pragma  mark - 刷新当前section
- (void)reloadCurrentSection:(UIButton *)btn
{
    self.isShow = !self.isShow;
        //取参
    id param = objc_getAssociatedObject(btn, "section");
    NSInteger section = [param integerValue];

    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:section];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        StudyRecordTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StudyRecordTypeCell"];
        [cell configWithDic:self.mainArray[indexPath.section]];

        return cell;
    } else {
        StudyRecordToolCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StudyRecordToolCell"];
        cell.delegate = self;
        NSDictionary *toolDic = self.mainArray[indexPath.section];
        [cell configWithDic:toolDic[@"tools"][indexPath.row - 1]];
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        CourseDetailController *courseVc = [[CourseDetailController alloc]init];
        courseVc.lessonId = self.mainArray[indexPath.row][@"lessonId"];
        [self.navigationController pushViewController:courseVc animated:YES];
    }
}
#pragma mark - 预览文件
- (void)quickLookFile:(NSString *)filePath
{
    QuickLookFileController *quickLookVc = [[QuickLookFileController alloc]init];
    quickLookVc.filePath = filePath;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:quickLookVc animated:YES];
}

- (NSArray *)mainArray
{
    return _mainArray ?:(_mainArray = [NSArray array]);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
